<template>
  <ele-modal
    :form="true"
    :destroy-on-close="true"
    width="400px"
    v-model="visible"
    title="设置学生所属辅导员"
  >
    <div>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        @submit.prevent=""
        :inline="true">
        <el-form-item label="辅导员" prop="counsellorCode">
          <el-select
            v-model="form.counsellorCode"
            collapse-tags
            clearable
            filterable
            placeholder="请选择辅导员">
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import {ref, reactive, watch} from 'vue';
import {EleMessage} from 'ele-admin-plus';
import {useFormData} from '@/utils/use-form-data';
import {addInfo, getUser, updateInfo, setLead} from "@/api/manage/statistic/admin/studentInfo/index.js";


const props = defineProps({
  /** 修改回显的数据 */
  data: Array
});

const emit = defineEmits(['done']);

/** 弹窗是否打开 */
const visible = defineModel({type: Boolean});

/** 提交状态 */
const loading = ref(false);

/** 表单实例 */
const formRef = ref(null);

/** 表单数据 */
const [form, resetFields, assignFields] = useFormData({
  ids: [],
  counsellorCode: ''
});

/** 表单验证规则 */
//todo 增加表单校验
const rules = reactive({
  counsellorCode: [
    {required: true, message: '请选择需要绑定的辅导员', trigger: 'blur'},
  ]
});

/** 关闭弹窗 */
const handleCancel = () => {
  visible.value = false;
}

/**
 * 保存
 */
const save = () => {
  formRef.value?.validate?.((valid) => {
    if (!valid) {
      return;
    }
    loading.value = true;
    setLead(form).then(res => {
      loading.value = false;
      EleMessage.success({message: res, plain: true});
      handleCancel();
      emit('done');
    }).catch((e) => {
      loading.value = false;
      EleMessage.error({message: e.message, plain: true});
    });
  });
};


const userOptions = ref([]);
const selectUser = () => {
  getUser().then(response => {
    userOptions.value = response.data;
  });
}


/** 监听弹窗打开 */
watch(visible, () => {
  if (visible.value) {
    //打开
    selectUser();
    if (props.data) {
      form.ids = props.data.map(item => item.id);
    }
  }
});

</script>
